<template>
  <div id="ArticleList">
    <!-- 搜索框 -->
    <div id="selectBar">
      <el-select v-model="searchPopularity" placeholder="请选择人气">
        <el-option v-for="(item, index) in popularityList" :key="index" :value="item" :label="item + '+'"></el-option>
      </el-select>
      <el-date-picker v-model="searchTime" type="date" placeholder="请选择发布时间"></el-date-picker>
      <el-input placeholder="请输入主题关键字" v-model="searchContent" clearable style="width: 180px;"></el-input>
      <el-select v-model="searchType" placeholder="请选择文章类型">
        <el-option v-for="item in typeData" :key="item.id" :label="item.name" :value="item.id"></el-option>
      </el-select>
      <el-button icon="el-icon-search" circle @click="search(true)" class="search"></el-button>
    </div>
    <!-- 表格 -->
    <el-table :data="articleData" stripe border class="el-table">
      <el-table-column prop="id" label="id" align="center"></el-table-column>
      <el-table-column label="文章封面" align="center">
        <template slot-scope="scope">
          <el-image :src="GLOBAL.OSSImageUrlRoot + 'headerImage/' + scope.row.id + '.png'" fit="contain"
            style="height: 80px;" :preview-src-list="[GLOBAL.OSSImageUrlRoot + 'headerImage/' + scope.row.id + '.png']">
            <div slot="error" class="image-slot">
              <i class="el-icon-picture-outline"></i>
            </div>
          </el-image>
        </template>
      </el-table-column>
      <el-table-column prop="theme" label="主题" align="center"></el-table-column>
      <el-table-column prop="introduction" label="介绍"></el-table-column>
      <el-table-column prop="initialTime" label="发布时间" align="center"></el-table-column>
      <el-table-column prop="lastTime" label="最后修改时间" align="center"></el-table-column>
      <el-table-column prop="popularity" label="人气" align="center"></el-table-column>
      <el-table-column prop="typeId" label="类型id" align="center"></el-table-column>
      <el-table-column label="操作" fixed="right" align="center">
        <template slot-scope="scope">
          <el-button @click="currentArticle = scope.row; ArticleFormShow = true;" type="primary" icon="el-icon-edit"
            size="mini"></el-button>
          <el-button @click="currentArticle = scope.row; ArticleDeleteShow = true;" type="primary" icon="el-icon-delete"
            size="mini"></el-button>
        </template>
      </el-table-column>
    </el-table>
    <!-- 分页按钮 -->
    <div id="paging">
      <el-pagination layout="prev, pager, next" :page-size="pageSize" :total="total" @current-change="pageCurrentChange">
      </el-pagination>
    </div>
    <!-- 删除提示框 -->
    <el-dialog title="提示" :visible.sync="ArticleDeleteShow" width="30%">
      <span>确定删除该文章么</span>
      <span slot="footer" class="dialog-footer">
        <el-button @click="ArticleDeleteShow = false;">取 消</el-button>
        <el-button type="primary" @click="deleteEssay(); ArticleDeleteShow = false;">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 编辑提示框 -->
    <el-dialog title="编辑文章" :visible.sync="ArticleFormShow">
      <el-form :model="currentArticle" label-position="top">
        <el-form-item>
          <span>id：{{ currentArticle.id }}</span>
        </el-form-item>
        <el-form-item label="封面图片上传/修改">
          <el-image :src="GLOBAL.OSSImageUrlRoot + 'headerImage/' + currentArticle.id + '.png'" fit="contain"
            style="height: 80px;"
            :preview-src-list="[GLOBAL.OSSImageUrlRoot + 'headerImage/' + currentArticle.id + '.png']">
            <div slot="error" class="image-slot">
              <i class="el-icon-picture-outline"></i>
            </div>
          </el-image>
          <el-upload class="upload-demo" :action="uploadUrl" :before-upload="beforeImgUpload" auto-upload
            :headers="imgUploadHeaders" :on-error="imgUploadError" :on-success="imgUploadSuccess" :limit="1"
            :on-exceed="handleExceed" accept=".jpg, .png" list-type="picture" :multiple="false" :file-list="fileList"
            name="file">
            <el-button size="small" type="primary">点击上传</el-button>
            <el-button size="small" type="danger" @click.stop="deleteImage">删除封面</el-button>
            <div slot="tip" class="el-upload__tip">只能上传jpg/png文件，无需点击提交自动上传</div>
          </el-upload>
        </el-form-item>
        <el-form-item label="主题">
          <el-input v-model="currentArticle.theme" type="input" clearable></el-input>
        </el-form-item>
        <el-form-item label="介绍">
          <el-input v-model="currentArticle.introduction" type="textarea" autosize></el-input>
        </el-form-item>
        <el-form-item label="人气">
          <el-input v-model="currentArticle.popularity" type="input" clearable></el-input>
        </el-form-item>
        <el-form-item label="发布时间">
          <el-date-picker type="date" placeholder="选择日期" v-model="currentArticle.initialTime"></el-date-picker>
        </el-form-item>
        <el-form-item label="最后修改时间">
          <span>{{ currentArticle.lastTime }}</span>
        </el-form-item>
        <el-form-item label="文章类型">
          <el-select v-model="currentArticle.typeId" placeholder="请选择文章类型">
            <el-option v-for="item in typeData" :key="item.id" :label="item.name" :value="item.id"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="更新文章内容">
          <el-upload class="upload-demo" :action="uploadFileUrl" :before-upload="beforeFileUpload" auto-upload
            :headers="imgUploadHeaders" :on-error="imgUploadError" :on-success="imgUploadSuccess" :limit="1"
            :on-exceed="handleExceed" accept=".md, .txt" :multiple="false" :file-list="ArticleFileList" name="file">
            <el-button size="small" type="primary">选择文件</el-button>
            <div slot="tip" class="el-upload__tip">只能上传md/txt文件，无需点击提交自动上传</div>
          </el-upload>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="ArticleFormShow = false">取 消</el-button>
        <el-button type="primary" @click="editArticleUpdate(); ArticleFormShow = false">提 交</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
export default {
  data() {
    return {
      articleData: [], // 文章数据
      currentArticle: {}, // 当前选择的文章数据
      ArticleFormShow: false, // 文章编辑提示框的显示/隐藏
      ArticleDeleteShow: false, // 文章删除提示框的显示/隐藏
      fileList: [], // 文件(图片)上传的文件list
      ArticleFileList: [], // 文件上传的文件list
      imgUploadHeaders: { 'Token': sessionStorage.getItem('token') }, // 请求头token信息，用于图片上传后端认证
      typeData: [], // 文章类型数据
      currentPage: 1, // 当前页
      pageSize: 10, // 页大小
      total: 0, // 数据总数
      searchContent: null, // 搜索主题内容
      searchTime: '', // 搜索时间
      searchType: '', // 搜索文章类型
      searchPopularity: '', // 搜索人气
      popularityList: [10, 50, 100, 1000, 5000, 10000], // 人气筛选列表
      searchOrNot: false, // 是否搜索状态量，用于确定翻页后数据从那个方法得到
    }
  },
  computed: {
    uploadUrl() { // 请求上传图片的url地址
      return this.$axios.defaults.baseURL + '/article/login/uploadArticleHeader/' + this.currentArticle.id
    },
    uploadFileUrl() { // 请求上传图片的url地址
      return this.$axios.defaults.baseURL + '/article/login/uploadArticleFile/' + this.currentArticle.id
    },
  },
  methods: {
    // 请求文章类型数据
    getArticleTypeData() {
      this.$axios({
        method: 'post',
        url: '/type/login/getAllTypeOnce'
      }).then(res => {
        this.typeData = res.data
      })
    },
    // 请求文章数据 分页
    getArticleData() {
      // 请求获取文章数据
      this.$axios({
        method: 'post',
        url: '/article/login/getAllArticle/' + this.currentPage + '/' + this.pageSize
      }).then(res => {
        res.data.data.data.forEach(element => { // 格式化文章时间
          element.initialTime = element.initialTime.slice(0, 10)
          element.lastTime = element.lastTime.slice(0, 10)
        });
        this.articleData = res.data.data.data
        this.total = res.data.data.total
      })
    },
    // 筛选搜索文章事件,参数意思：表示是翻页查找(不需要重设页状态)，还是按钮点击查找(需要重设页状态)
    search(buttonSearchOrNot) {
      if (buttonSearchOrNot) { // 若为按钮点击搜索,重设页状态
        this.currentPage = 1
        this.total = 0
      }
      this.searchOrNot = true // 改变搜索状态量
      let data = new FormData()
      if (this.searchTime != '' && this.searchTime != null) {
        data.append("initialTime", this.searchTime)
      }
      if (this.searchContent == '') {
        this.searchContent = null
      }
      data.append("typeId", this.searchType)
      data.append("popularity", this.searchPopularity)
      this.$axios({
        method: 'post',
        url: '/article/login/searchArticleByScreen/' + this.searchContent + '/' + this.currentPage + '/' + this.pageSize,
        data: data,
        headers: {
          'Content-Type': 'application/x-www-form-urlencoded'
        }
      }).then(res => {
        res.data.data.data.forEach(element => { // 格式化文章时间
          element.initialTime = element.initialTime.slice(0, 10)
          element.lastTime = element.lastTime.slice(0, 10)
        });
        this.articleData = res.data.data.data
        this.total = res.data.data.total
      })
    },
    // 删除文章
    deleteEssay() {
      this.$axios({
        method: 'post',
        url: '/article/login/deleteArticle/' + this.currentArticle.id,
      }).then(res => {
        if (res.data) {
          this.$router.go(0)
          this.$message({
            type: 'success',
            message: '删除成功',
            showClose: true,
          })
        } else {
          this.$message({
            type: 'error',
            message: '删除失败！出现错误了X.X',
            showClose: true,
          })
        }
      })
    },
    // 处理图片上传多了的提示事件
    handleExceed() {
      this.$message({
        type: 'error',
        message: '限制只能上传一个文件哦',
        showClose: true,
      })
    },
    // 图片文件上传出现错误的提示事件
    imgUploadError() {
      this.$message({
        message: '文件上传出现错误X.X',
        type: 'error',
        showClose: true,
      })
    },
    // 图片文件上传成功的提示事件
    imgUploadSuccess() {
      this.$message({
        message: '上传成功',
        type: 'success',
        showClose: true
      })
    },
    // 图片文件上传前的文件类型检查
    beforeImgUpload(file) {
      if (this.getfileName(file.name) != '.jpg' && this.getfileName(file.name) != '.png') {
        this.$message({
          message: '上传封面图片文件格式只能为jpg或png',
          type: 'error',
          showClose: true,
        })
        return false
      }
    },
    // 获取文件后缀工具函数
    getfileName(filename) {
      // 转换为小写
      const pos = filename.toLowerCase().lastIndexOf('.')
      let suffix = ''
      if (pos !== -1) {
        suffix = filename.substring(pos)
      }
      return suffix
    },
    // 提交编辑的文章内容事件
    editArticleUpdate() {
      if (this.currentArticle.initialTime == '' || this.currentArticle.initialTime == null) {
        this.$message({
          message: '发布时间不能为空',
          type: 'error',
          showClose: true
        })
        return
      }
      let data = new FormData()
      data.append("id", this.currentArticle.id)
      data.append("theme", this.currentArticle.theme)
      data.append("introduction", this.currentArticle.introduction)
      data.append("initialTime", new Date(this.currentArticle.initialTime))
      data.append("typeId", this.currentArticle.typeId)
      data.append("popularity", this.currentArticle.popularity)
      this.$axios({
        method: 'post',
        url: '/article/login/updateArticle',
        data: data,
        headers: {
          'Content-Type': 'application/x-www-form-urlencoded'
        }
      }).then(res => {
        if (res.data) {
          this.$router.go(0)
          this.$message({
            message: '提交成功',
            type: 'success',
            showClose: true,
          })
        } else {
          this.$message({
            message: '提交失败！出现错误了X.X',
            type: 'success',
            showClose: true,
          })
        }
      })
    },
    // 翻页事件
    pageCurrentChange(val) {
      this.currentPage = val // 更改当前页
      if (this.searchOrNot) { // 若搜索过，就用筛选搜索的方式查询数据
        this.search(false)
        return
      }
      this.getArticleData()
    },
    // 删除文章封面
    deleteImage() {
      this.$axios({
        method: 'post',
        url: '/article/login/deleteImage/' + this.currentArticle.id
      }).then(res => {
        if (res.data) {
          this.$message({
            showClose: true,
            message: '删除成功',
            type: 'success'
          })
        } else {
          this.$message({
            showClose: true,
            message: '删除失败，出现错误了X.X',
            type: 'error'
          })
        }
      })
    },
    // 在文件更新上传之前
    beforeFileUpload(file) {
      if (this.getfileName(file.name) != '.txt' && this.getfileName(file.name) != '.md') {
        this.$message({
          message: '上传文件格式只能为txt或md',
          type: 'error',
          showClose: true,
        })
        return false
      }
    }
  },
  mounted() {
    this.getArticleData()
    this.getArticleTypeData()
  }
}
</script>

<style lang="scss" scoped>
#selectBar {
  margin: 20px auto;
  display: flex;
  justify-content: center;
}
</style>
<style scoped="scoped">
/* 表格 */
.el-table {
  width: 80%;
  margin: 0 auto;
  border-radius: 20px;
}

.el-table__row {
  background-color: rgba(0, 0, 0, 0);
}

/deep/.el-table--border {
  border-color: #464646;
}

/deep/.el-table th.el-table__cell.is-leaf {
  border-color: #464646;
}

/deep/ .el-table thead tr>th {
  background-color: #202020 !important;
  color: #464646;
  border-color: #464646;
}

/deep/ .el-table tbody tr>td {
  background-color: #202020 !important;
  border-color: #464646;
}

/deep/.el-table::before,
/deep/.el-table__fixed-right::before {
  background-color: rgba(0, 0, 0, 0);
}

/deep/.el-table__empty-block {
  background-color: #202020;
}

.cell .el-button--primary {
  margin-bottom: 10px;
}

/deep/.el-table__body-wrapper {
  border-bottom: 1px solid;
}

/* 分页 */

/deep/.el-pagination {
  display: flex;
  justify-content: center;
  margin: 20px auto;
  color: #202020;
}

/deep/.el-pagination button {
  color: #fff;
  background-color: #202020;
}

/deep/ .el-pager li.active {
  color: rgb(255, 150, 50);
}

/deep/ .number {
  color: #fff;
}

/deep/ .number:hover {
  color: rgb(255, 150, 50);
}

/deep/.el-pager li {
  background-color: #202020;
}

/* 搜索Bar */
.search {
  background-color: #202020;
  color: #fff;
}

/deep/#selectBar .el-input__inner {
  background-color: #202020;
  color: #fff;
}

/deep/.inputMoodName>.el-input__inner {
  background-color: #fff;
}

#selectBar .el-input,
#selectBar .el-select {
  margin: 0 20px;
}
</style> 
